<?php
class BooksModel extends Db_Table{

	function __construct()
	{
		parent::__construct("books");
	}
	
	
	public function getMaxId(){
		
		$sql = "SELECT MAX(id) as max_id FROM ".$this->table;
		$result = $this->db->getField($sql);
		return (int)$result;	
	}

	public function getBooksList($where=array(),$pager = 100000, $sort=array()){
		$map = array(
            'id'			=>	'b.id',
			'title'			=>	'b.title',
			'author'		=>	'b.author',
			'publishing'	=>	'b.publishing',
			'isbn'			=>	'b.isbn',
			'year'			=>	'b.year',
			'genre_id'		=>	'b.genre_id',
			'series_id'		=>	'b.series_id',
			'description'	=>	'b.description',
			'genre_name'	=>	'(SELECT g.title FROM genre AS g WHERE g.id = b.genre_id)',
		);

		$sql = 'SELECT COUNT(*) FROM '.$this->table.' AS b ' 
			.'WHERE '.$this->_parseWhere($where, $map);
			
        $cnt = $this->db->getField($sql);
		if (!$cnt)
            return array();
		if ($pager){
            if (is_object($pager))
                $limit = $pager->init($cnt);
            else 
                $limit = intVal($pager);
        }

		$sql = "SELECT "
            .$this->_joinFields($map)
            ." FROM ".$this->table." AS b "
			."WHERE ".$this->_parseWhere($where, $map)." "
            .$this->_parseOrder($sort)
            ." LIMIT ".$limit."";
		return $this->db->getRows($sql);
	}	
}